﻿using System;
using System.Security.Principal;
using System.Web.Mvc;
using System.Web.Security;

namespace Gp.Examples.FullCalendar.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {

        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.

        public AccountController()
            : this(null, null)
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments at the end of this file for more
        // information.
        public AccountController(IFormsAuthentication formsAuth, IMembershipService service)
        {
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
            MembershipService = service ?? new AccountMembershipService();
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        public ActionResult LogOn()
        {
            if (Membership.Provider.Name == "LiveIdMembershipProvider")
            {
                Response.Redirect("/Authentication/LiveIdHandler.ashx?action=login");
                Response.End();
            }
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(string userName, string password)
        {
            if (!(string.IsNullOrEmpty(password)) && !(string.IsNullOrEmpty(password)))
            {
                if (MembershipService.ValidateUser(userName, password))
                {
                    FormsAuth.SignIn(userName, false);
                    return RedirectToAction("Index", "Home");
                }
            }

            //Credential were not provided, return to the view
            return View();
        }

        public ActionResult LogOff()
        {
            if (Membership.Provider.Name == "LiveIdMembershipProvider")
            {
                Response.Redirect("/Authentication/LiveIdHandler.ashx?action=logout");
                Response.End();
            }

            FormsAuthentication.SignOut();
            Session.Remove("UserId");
            return RedirectToAction("Index", "Home");
            return View();
        }

        public ActionResult Register()
        {

            if (Membership.Provider.Name == "LiveIdMembershipProvider")
            {
                var password = Session["LiveId"] as string;
                if (string.IsNullOrEmpty(password))
                {
                    Response.Redirect("/LiveIdHandler.ashx?action=login");
                    Response.End();
                }
            }
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;


            return View("Register");
        }

        [HttpPost]
        public ActionResult Register(string userName, string email, string password, string confirmPassword)
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            string liveID = Session["LiveId"] as string;
            if (Membership.Provider.Name == "LiveIdMembershipProvider")
            {
                if (string.IsNullOrEmpty(liveID))
                {
                    Response.Redirect("/Authentication/LiveIdHandler.ashx?action=login");
                    Response.End();
                }

                //As LiveId users don't provide password during registration
                //We manually force the password in order to pass the model validation
                password = liveID;
                confirmPassword = liveID;
            }


            if (ValidateRegistration(userName, email, password, confirmPassword))
            {
                MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email, liveID);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuth.SignIn(userName, false);
                    Session["UserName"] = userName;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }


            return View();
        }

        public ActionResult Cancel()
        {
            FormsAuthentication.SignOut();
            Session.Remove("LiveId");
            Session.Remove("UserName");
            Response.Cookies.Clear();
            return new RedirectResult("/");
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }
            var user = Membership.GetUser(userName);
            if (user != null)
            {
                ModelState.AddModelError("username", "Selected username is already taken.");
            }
            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", "You must specify an email address.");
            }

            if (String.IsNullOrEmpty(password) || String.IsNullOrEmpty(confirmPassword))
            {
                ModelState.AddModelError("password", "You must specify a password.");
                ModelState.AddModelError("confirmPassword", "You must specify a confirm password.");
            }
            else
            {
                if (password != confirmPassword)
                {
                    ModelState.AddModelError("confirmPassword", "Confirm password must match password");
                }
            }


            return ModelState.IsValid;
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }

}